# 数据分析题目解答(建议先赞后看，养成习惯 如果不赞，先拉出去枪毙两分钟 作者：小匠IT)
import pandas as pd
import matplotlib.pyplot as plt
import os
from io import BytesIO
from PIL import Image

# 设置输出文件夹路径
output_folder = r'output/48'
os.makedirs(output_folder, exist_ok=True)

# 直通车推广数据
data_straight_train = {
    '日期': ['1.10-1.31', '2.1-2.29', '3.1-3.31', 'Q1'],
    '展现量': [2068298, 1741772, 2058940, 5869010],
    '花费': [27904.34, 25340.12, 36912.40, 90156.86],
    '点击量': [15006, 18157, 24033, 57196],
    '总成交金额': [105035.87, 51194.83, 135584.47, 291815.17],
    '总成交笔数': [540, 192, 600, 1332]
}

df_straight_train = pd.DataFrame(data_straight_train)

# 计算投入产出比和点击转化率
df_straight_train['投入产出比'] = (df_straight_train['总成交金额'] / df_straight_train['花费']).round(2)
df_straight_train['点击转化率'] = ((df_straight_train['总成交笔数'] / df_straight_train['点击量']) * 100).round(2)

# 钻展推广数据
data_diamond_exhibition = {
    '时间': ['1月', '2月', '3月', '总计'],
    '消耗': [45802.89, 31076.09, 65517.67, 142396.65],
    '成交订单金额': [388452.12, 128490.54, 398546.47, 915489.13]
}

df_diamond_exhibition = pd.DataFrame(data_diamond_exhibition)
df_diamond_exhibition['投入产出比'] = (df_diamond_exhibition['成交订单金额'] / df_diamond_exhibition['消耗']).round(2)

# 绘制并保存图表
def save_chart(fig, filename):
    fig.savefig(filename, format='png', bbox_inches='tight')
    plt.close(fig)

# 设置中文字体路径（请根据实际路径调整）
plt.rcParams['font.sans-serif'] = ['SimSun']  # 使用宋体
plt.rcParams['axes.unicode_minus'] = False  # 正常显示负号

# 直通车投入产出比图表
fig1, ax1 = plt.subplots(figsize=(10, 6))
ax1.plot(df_straight_train['日期'], df_straight_train['投入产出比'], marker='o', label='投入产出比')
ax1.set_title('直通车投入产出比')
ax1.set_xlabel('日期')
ax1.set_ylabel('投入产出比')
ax1.legend()
ax1.grid(True)
save_chart(fig1, os.path.join(output_folder, '直通车投入产出比.png'))

# 直通车点击转化率图表
fig2, ax2 = plt.subplots(figsize=(10, 6))
ax2.plot(df_straight_train['日期'], df_straight_train['点击转化率'], marker='o', label='点击转化率')
ax2.set_title('直通车点击转化率')
ax2.set_xlabel('日期')
ax2.set_ylabel('点击转化率 (%)')
ax2.legend()
ax2.grid(True)
save_chart(fig2, os.path.join(output_folder, '直通车点击转化率.png'))

# 钻展投入产出比图表
fig3, ax3 = plt.subplots(figsize=(10, 6))
ax3.bar(df_diamond_exhibition['时间'], df_diamond_exhibition['投入产出比'], color='skyblue')
ax3.set_title('钻展投入产出比')
ax3.set_xlabel('时间')
ax3.set_ylabel('投入产出比')
ax3.grid(True)
save_chart(fig3, os.path.join(output_folder, '钻展投入产出比.png'))

print(f"\n包含分析结果的图表已保存到 {output_folder}")